import {DateModel, DataModel, StatusModel,MsgModel, sequelize} from '../until/context'
import {Op, QueryTypes} from 'sequelize'
import Tool from '../until/tool'
import dayjs from 'dayjs'
import port from "../../config"
interface IfindParmas {
    model: any, // 数据库模型
    startPosition: number, //查询的起始位置
    limit: number, // 查询限制的条数
    where: object, // 查询的条件
    attributes: Array<string>, // 查询的属性
    multi?: boolean; // 默认是当个
}
class AdminService {
    public static async myFindAll(options: IfindParmas) {
        let {startPosition,limit,where,attributes,model}:{startPosition: number, limit: number, where: Object,attributes: Array<string>,model:any}  = options
        if (options.multi) {
            let {rows,count} = await model.findAndCountAll({
                attributes,
                where: {
                    [Op.and]: {
                        ...where
                    }
                },
                offset: startPosition,
                limit
            })
            return {total: count, data: rows}
        } else {
            let res = await model.findAndCountAll({
                attributes,
                where: {
                    ...where
                },
                offset: startPosition,
                limit
            })
            return {total: res.count, data:res.rows}
        }

    }
    // 获取数据列表
    async getDataList(pageSize,page,query) {
        let startPosition:number = (page - 1)*pageSize  // 查询的起始位置
        let total:number = 0
        if (query !=='') {
            let data = await DataModel.findAll({
                attributes: ["uvc","inf","tem","hum","pre","createdAt","module_id"],
                where: {
                    date: query
                },
                offset: startPosition,
                limit: pageSize
            })
            total = await DataModel.count({
                where: {
                    date: query
                }
            })
            return {data,total}
        } else {
            try {
                let data = await DataModel.findAll({
                    attributes: ["uvc","inf","tem","hum","pre","createdAt","module_id"],
                    offset: startPosition,
                    limit: pageSize
                })
                total = await DataModel.count()
                return {data,total}
            } catch(err) {
                console.log(err)
            }

        }
    }
    async getStatusDataList(pageSize,page,queryDate,queryType) {
        let startPosition:number = (page - 1) * pageSize  // 查询的起始位置
        let total:number = 0
        if (queryDate !=='' && queryType !== '') {
            let data = await StatusModel.findAll({
                attributes: ["uvc_sta","ir_sta","temp_sta","hum_sta","pre_sta","createdAt","module_id"],
                where: {
                    [Op.and]: {
                        date: queryDate,
                        [Op.or]: {
                            uvc_sta: queryType,
                            ir_sta: queryType,
                            temp_sta: queryType,
                            hum_sta: queryType,
                            pre_sta: queryType
                        }
                    }
                },
                offset: startPosition,
                limit: pageSize
            })
            total = await StatusModel.count({
                where: {
                    [Op.and]: {
                        date: queryDate,
                        [Op.or]: {
                            uvc_sta: queryType,
                            ir_sta: queryType,
                            temp_sta: queryType,
                            hum_sta: queryType,
                            pre_sta: queryType
                        }
                    }
                }
            })
            return {data,total}
        } else if(queryDate === '' && queryType !== '') {
            let data = await StatusModel.findAll({
                attributes: ["uvc_sta","ir_sta","temp_sta","hum_sta","pre_sta","createdAt","module_id"],
                where: {
                    [Op.or]: [
                        { uvc_sta: queryType},
                        { ir_sta: queryType},
                        {hum_sta: queryType},
                        {temp_sta: queryType},
                        {pre_sta: queryType}
                    ]
                },
                offset: startPosition,
                limit: pageSize
            })
            total = await StatusModel.count({
                where: {
                    [Op.or]: [
                        { uvc_sta: queryType},
                        { ir_sta: queryType},
                        {hum_sta: queryType},
                        {temp_sta: queryType},
                        {pre_sta: queryType}
                    ]
                }
            })
            return {data,total}
        } else if (queryDate !== '' && queryType == '') {
            let data = await StatusModel.findAll({
                attributes: ["uvc_sta","ir_sta","temp_sta","hum_sta","pre_sta","createdAt","module_id"],
                where: {
                    date: queryDate
                },
                offset: startPosition,
                limit: pageSize
            })
            total = await StatusModel.count({
                where: {
                    date: queryDate
                }
            })
            return {data,total}
        } else {
            let data = await StatusModel.findAll({
                attributes: ["uvc_sta","ir_sta","temp_sta","hum_sta","pre_sta","createdAt","module_id"],
                offset: startPosition,
                limit: pageSize
            })
            total = await StatusModel.count()
            return {data,total}
        }
    }
    // 获取可以下载的日期
    async downLoadDate() {
        return await DateModel.findAll({
            attributes: ["rid","currentDate"]
        })
    }

    // 下载运行时的数据并且导入成为excel
    async downloadRunData(date) {
        let data = await DataModel.findAll({
            attributes: ["uvc","inf","tem","hum","pre","date","time","module_id"],
            where: {
                date
            }
        })
        return data
    }

    async getItem(date) {
        return await DataModel.count({
            where: {
                date
            }
        })
    }
       //数据保存
       async saveDataList(data) {
        await DataModel.create({
            ...data,
            time: new Date().toLocaleTimeString(),
            date: Tool.getCurrentDate()
        })
     }

     //数据状态保存
     async saveStatusList(data) {
        await StatusModel.create({
            ...data,
            time: new Date().toLocaleTimeString(),
            date: Tool.getCurrentDate()
        })
     }
     async addRunDate() {
        // @ts-ignore
        await DateModel.create({
            currentDate: Tool.getCurrentDate()
        })
     }
    async getModuleNum() {
        let maxId = await DataModel.max("module_id")
        return maxId
    }
    // 获取分析报告
    async getAnayleRecord(startTime: string,endTime: string,module_id: number,module_type: string,selectDate:string) {
        console.log(`select ${module_type},strftime('%Y-%m-%d %H:%M:%S',createdAt,'localtime') as timer,time from Data where module_id=${module_id}  and timer > '${startTime}' and timer < '${endTime}'`)
        let data = await sequelize.query(`select ${module_type},
        strftime('%Y-%m-%d %H:%M:%S',createdAt,'localtime') as timer,
        time from Data where module_id=${module_id} 
        and date='${selectDate}' and timer > '${startTime}' and timer < '${endTime}'`,{type: QueryTypes.SELECT})
        return data
    }

    async getHistryList(module_id,type) {
        let date = Tool.getCurrentDate()
        let count = await DateModel.findAll({
            where: {
                [Op.not]: {
                    currentDate: date
                }
            },
            limit: 4
        })
        let dateList = count.map(item => item.dataValues.currentDate)
        let errNum = []
        for(let i=0;i<dateList.length;i++) {
           let num:any = await StatusModel.count({
                where: {
                    module_id,
                    date: dateList[i],
                    [type]: 1
                }
            })
            //@ts-ignore
            errNum.push(num)
        }
        return {
            dateList,
            errNum
        }
    }
    // 判断是否可以删除数据，最多报错一个礼拜的数据
    async isDel() {
        let res = await DateModel.count()
        return res > 7
    }
    async deleteData() {
        let result = await DateModel.findAll({
            limit: 7,
            order: [
                ["createdAt","desc"]
            ]
        })
        let dateList = result.map(item => item.currentDate)

        // 删除日期数据
        await DateModel.destroy({
            where: {
                currentDate: {
                    [Op.not]: dateList
                }
            }
        })
        // 删除状态数据
        await StatusModel.destroy({
            where: {
                date: {
                    [Op.not]: dateList
                }
            }
        })

        // 删除运行数据
        await DataModel.destroy({
            where: {
                date: {
                    [Op.not]: [dateList]
                }
            }
        })
    }

    // 获取系统报警信息
    async getErrorList(page: number,pageSize: number,queryDate: string,queryType:string,keywords:string) {
        let startPosition:number = (page - 1)*pageSize  // 查询的起始位置
        let total:number = 0
        if (queryDate && queryType && keywords) {
            let {rows,count} = await MsgModel.findAndCountAll({
                attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                offset: startPosition,
                limit: pageSize,
                where: {
                    date: queryDate,
                    state: queryType,
                    info: {[Op.like]: `%${keywords}%`}
                }
            })
            return {data: rows,total: count}
        }
        else if(queryType && keywords && !queryDate) {
            let {rows,count} = await MsgModel.findAndCountAll({
                attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                offset: startPosition,
                limit: pageSize,
                where: {
                    [Op.and]: {
                        state: queryType,
                        info: {
                            [Op.like]: `%${keywords}%`
                        }
                    }
                }
            })
            return {data: rows,total: count}
        }
        else if(queryDate && keywords && !queryType) {
            let {rows,count} = await MsgModel.findAndCountAll({
                attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                offset: startPosition,
                limit: pageSize,
                where: {
                    [Op.and]: {
                        date: queryDate,
                        info: {
                            [Op.like]: `%${keywords}%`
                        }
                    }
                }
            })
            return {total: count, data:rows}
        }
        else if (queryDate && queryType && !keywords) {
            let result: {data:any,total: number} = await AdminService.myFindAll({
                model: MsgModel,
                attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                startPosition,
                where: {date: queryDate, state: queryType},
                limit: pageSize
            })
            return result
        }
        else if (queryDate && !queryType && !keywords) {
            let result: {data:any,total:number} = await AdminService.myFindAll({
                model: MsgModel,
                attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                startPosition,
                where: {date: queryDate},
                limit: pageSize
            })
            return result
        }
        else if (queryType && !queryDate && !keywords) {
            let result: {data:any,total:number} = await AdminService.myFindAll({
                model: MsgModel,
                attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                startPosition,
                where: {state: queryType},
                limit: pageSize
            })
            return result
        }
        else if(keywords && !queryType && !queryDate) {
            try {
                let data = await MsgModel.findAll({
                    attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                    where: {
                        info: {[Op.like]: `%${keywords}%`}
                    },
                    limit: pageSize,
                    offset: startPosition,
                })
                let total = await MsgModel.count({
                    attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                    where: {
                        info: {[Op.like]: `%${keywords}%`}
                    }

                })
                return {data,total}
            } catch (err) {
                console.log(err)
            }

        }
        else {
            try {
                let data = await MsgModel.findAll({
                    attributes: ["createdAt","info","rid","level","date","state","module_id","type_id","error_value"],
                    offset: startPosition,
                    limit: pageSize
                })
                total = await MsgModel.count()
                return {data,total}
            } catch(err) {
                console.log(err)
            }

        }
    }

    // 添加报警信息
    async addErrorInfo(module_id: number,info: string,level:number,date: string,state: number,error_value: number,type_id: number) {
        let res = await MsgModel.create({
            module_id,
            info,
            date,
            state,
            level,
            error_value,
            type_id
        })
        return res
    }

    async removeErrorRecord(rid:number) {
        let res: number = await MsgModel.destroy({
            where: {
                rid
            }
        })
        return res
    }
    async updateErrorState(rid:number,state:number) {
        let res = await MsgModel.update({state},{
            where: {
                rid
            }
        })
        return res[0]
    }

    async getErrorNum(p1,p2,p3) {
       let num1 = await MsgModel.count({
           where: {
               date: p1
           }
       })
       let num2 = await MsgModel.count({
           where: {
               createdAt: {
                   [Op.between]: [p2,dayjs().format('YYYY-MM-DD')]
               }
           }
       })
        let num3 = await MsgModel.count({
            where: {
                createdAt: {
                    [Op.between]: [p3,dayjs().format('YYYY-MM-DD')]
                }
            }
        })
        return [num1,num2,num3]
    }
    // 获取监测点的报警次数排行
    async getSortPoint() {
        let res = await MsgModel.count({
            group: ["module_id"]
        })
        let result = [...res]
        //@ts-ignore
        let id_list:number[] = res.map(item => item.module_id)
        //@ts-ignore
        if (port.moduleNum > 10) {
            //@ts-ignore
            for (let i = 0; i < 10; i++) {
                if (id_list.includes(i+1)) continue
                result.push({
                    module_id: i + 1,
                    count: 0
                })
            }
        } else {
            //@ts-ignore
            for (let i = 0; i <port.moduleNum; i++) {
                if (id_list.includes(i+1)) continue
                result.push({
                    module_id: i + 1,
                    count: 0
                })
            }
        }

       return result.sort((a, b) => b.count - a.count)
    }
}

export default new AdminService()
